package com.wo.cloud.gateway.config;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.wo.cloud.gateway.util.Oauth2Constant;
import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;
import java.time.Duration;

/**
 * @author liry
 * @version 1.0
 * @date Created on 2021/3/31 9:03
 * Description: 用户登录成功后存储token
 */

@Component
public class RouteConfig {

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * 登录路由，当用户登录成功后，将token存储到redis中
     *
     * @param builder
     * @return
     */
    @Bean
    public RouteLocator routes(RouteLocatorBuilder builder) {

        return builder.routes()
                .route("oauth-route-id", r -> r.path("/oauth/**")
                        .filters(f -> f.modifyResponseBody(String.class, String.class, (exchange, s) -> {
                            // exchange是请求和响应的封装，s是响应体
                            String path = exchange.getRequest().getPath().value();
                            if (path.equalsIgnoreCase("/oauth/token")) {
                                // 为登录请求，则获取其响应结果中的token
                                System.out.println("-----获取登录成功之后的token信息: " + s);
                                JSONObject response = JSON.parseObject(s);
                                if (ObjectUtil.isNotNull(response) && ObjectUtil.isNotNull(response.getString("data"))) {
                                    JSONObject jsonObject = JSON.parseObject(response.getString("data"));

                                    String accessToken = jsonObject.getString("access_token");
                                    // 获取有效时间
                                    Long expiresIn = jsonObject.getLong("expires_in");
                                    // 获取用户Id
                                    String userId = jsonObject.getString("user_id");
                                    if (StrUtil.isNotBlank(accessToken)) {
                                        // 加入到redis
                                        redisTemplate.opsForValue().set(Oauth2Constant.REDIS_TOKEN_PREFIX + accessToken, userId, Duration.ofSeconds(expiresIn));
                                    }
                                }
                            }

                            return Mono.just(s);
                        })).uri("lb://auth"))
                .build();
    }
}
